package testshuju;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.util.Log;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/17.
 */
public class ChaXunActivity extends SQLiteOpenHelper {


    private static final String DB_NAME = "scanner.db";
    private static final int DB_VERSION = 2;

    private static final String HISTORY_TABLE_NAME = "history";
    private static final String HISTORY_KEY_RECORD_ID= "_id";
    private static final String HISTORY_KEY_QR_TYPE = "qr_type";
    private static final String HISTORY_KEY_QR_CONTENT = "qr_content";
    private static final String HISTORY_KEY_QR_FROM = "qr_from";
    private static final String HISTORY_KEY_QR_TIME = "qr_time";

    private static final String CRATE_HISTORY_TABLE_SQL = "CREATE TABLE " + HISTORY_TABLE_NAME + " ("
            + HISTORY_KEY_RECORD_ID  +" INTEGER PRIMARY KEY AUTOINCREMENT, "
            + HISTORY_KEY_QR_TYPE +" TINYINT,"
            + HISTORY_KEY_QR_CONTENT +" TEXT,"
            + HISTORY_KEY_QR_FROM +" BOOLEAN,"
            + HISTORY_KEY_QR_TIME +" DATETIME DEFAULT (datetime('now','localtime')))";

    public ChaXunActivity(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CRATE_HISTORY_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + HISTORY_TABLE_NAME);
        onCreate(db);
    }

    private SQLiteDatabase getDatabase(){
        SQLiteDatabase db = null;
        try{
            db = getWritableDatabase();
        } catch (SQLiteException e){
            Log.e("SamLog","数据库操作失败");
            e.printStackTrace();
        }
        return db;
    }

    /**
     * 插入一条记录到数据库
     * @param recordEntity
     * @return
     */
    public boolean insertRecord(RecordEntity recordEntity){
        ContentValues contentValues = new ContentValues();
        if(recordEntity.getId() > 0) contentValues.put(HISTORY_KEY_RECORD_ID,recordEntity.getId());
        RecordEntity.RECORD_TYPE recordType = recordEntity.getRecordType();
        contentValues.put(HISTORY_KEY_QR_TYPE,recordType.getTypeValue());
        if(recordType == RecordEntity.RECORD_TYPE.CONTACT){
            contentValues.put(HISTORY_KEY_QR_CONTENT,(ContactEntity.toVCardFormat((ContactEntity)recordEntity.getRecordContent())));
        } else {
            contentValues.put(HISTORY_KEY_QR_CONTENT,((String)recordEntity.getRecordContent()));
        }
        contentValues.put(HISTORY_KEY_QR_FROM,recordEntity.getRecordFrome().getValue());
        contentValues.put(HISTORY_KEY_QR_TIME,recordEntity.getRecordTime());
        return getDatabase().insert(HISTORY_TABLE_NAME,null,contentValues) != -1;
    }

    /**
     * 删除一条记录
     * @param recordId
     */
    public void deleteRecord(int recordId){
        getDatabase().delete(HISTORY_TABLE_NAME,HISTORY_KEY_RECORD_ID + " = "+recordId,null);
        getDatabase().delete(HISTORY_TABLE_NAME,HISTORY_KEY_RECORD_ID + " = ?",new String[]{recordId+""});
    }

    public List<RecordEntity> getAllRecords(){
        Cursor cursor = getDatabase().rawQuery("SELECT * FROM " + HISTORY_TABLE_NAME,null);
        List<RecordEntity> recordEntityList = null;
        if(cursor != null) {
            recordEntityList = new ArrayList<>();
            while (cursor.moveToNext()) {
                RecordEntity recordEntity = new RecordEntity();
                recordEntity.setId(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_RECORD_ID)));
                RecordEntity.RECORD_TYPE recordType = RecordEntity.RECORD_TYPE.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                recordEntity.setRecordType(recordType);
                String contentStr = cursor.getString(cursor.getColumnIndex(HISTORY_KEY_QR_CONTENT));
                if(recordType == RecordEntity.RECORD_TYPE.CONTACT){
                    recordEntity.setRecordContent(ContactEntity.parseFromVCard(contentStr));
                } else recordEntity.setRecordContent(contentStr);
                RecordEntity.RECORD_FROM recordFrom = RecordEntity.RECORD_FROM.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_QR_TYPE)));
                recordEntity.setRecordFrome(recordFrom);
                String time = cursor.getString(cursor.getColumnIndex(HISTORY_KEY_QR_TIME));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long timeStamp = System.currentTimeMillis();
                try {
                    timeStamp = simpleDateFormat.parse(time).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                recordEntity.setRecordTime(timeStamp);
                recordEntityList.add(recordEntity);
            }
        }
        return recordEntityList;
    }
}
